package com.diankangwo.controller;

import com.diankangwo.constant.PayStatus;
import com.diankangwo.constant.PayType;
import com.diankangwo.constant.resultMsg;
import com.diankangwo.dao.*;
import com.diankangwo.domain.*;
import com.diankangwo.util.BeecloudPayUtil;
import com.diankangwo.util.GuidUtil;
import com.diankangwo.util.OrderUtil;
import com.diankangwo.util.PageSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户充值记录
 */
@Controller
@Api(description = "用户充值记录")
public class UserWalletController {

    @Autowired
    private UserDAO userDao;

    @Autowired
    private UserWalletDao uwDao;

    @Autowired
    private WalletPayLogDAO wplDao;

    @Autowired
    private OrderDAO orderDao;

    @Autowired
    public static PhoneAndCodeDAO phoneAndCodeDao;

    @Autowired
    private DistributionDAO distributionDAO;

    @Resource
    private ReflectionSaltSource saltSource;

    @Resource
    private ShaPasswordEncoder passwordEncoder;

    @Autowired
    private MinmoneylimitDAO minmoneylimitDAO;
    @Autowired
    private OnlinePayLogDAO onlinePayLogDAO;

    /**
     * 获取指定用户钱包信息
     *
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = "获取指定用户钱包信息", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/wallet/userWalletInfo", method = RequestMethod.GET)
    public String userWalletInfo(String accessToken) {
        UserInfo user = uwDao.findByUserWallet(accessToken);
        String code = "2";
        String msg = "处理异常！";
        if (user != null) {
            code = "1";
            msg = "查询成功！";
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, user);
    }

    /**
     * 获取指定用户充值/提现记录
     *
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = "获取指定用户充值记录", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/wallet/userWalletInfoList", method = RequestMethod.GET)
    public String userWalletInfoList(String accessToken, String type) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        List<WalletPayLog> wplList = null;
        if (user != null) {
            wplList = wplDao.getWalletPayLogList(user.getId(), type);
            code = "1";
            if (wplList != null) {
                msg = "查询成功！";
            } else {
                msg = "未查询到充值记录！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, wplList);
    }

    /**
     * 查询用户钱包记录
     *
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = "查询用户钱包购物记录", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/wallet/userShoppingLog", method = RequestMethod.GET)
    public String userShoppingLog(String accessToken, int pageNo, int pageSize) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        PageSupport<Order> orderList = null;
        if (user != null) {
            orderList = orderDao.findByUid(user.getUid(), pageNo, pageSize);
            code = "1";
            if (orderList != null) {
                msg = "查询购物记录成功！";
            } else {
                msg = "未查询到购物信息！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, orderList != null ? orderList.getResultData() : null);
    }

    /**
     * 充值
     *
     * @param accessToken
     * @param totalTee
     * @return
     */
    @ApiOperation(value = "充值", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "totalTee", value = "充值金额", required = true, dataType = "long")
    })
    @ResponseBody
    @RequestMapping(value = "/wallet/pay", method = RequestMethod.GET)
    public String pay(String accessToken, float totalTee) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        BeecloudPayUtil butil = new BeecloudPayUtil();
        Map<String, Object> optional = new HashMap<>();
        String billNo = OrderUtil.getOrderNo();
        optional.put("type", "userWallet");
        Order order = new Order();
        //0.判断用户token
        if (user != null) {
            //1.存入交易记录
            WalletPayLog walletPayLog = new WalletPayLog();
            walletPayLog.setBillNo(billNo);
            walletPayLog.setCreateTimestamp(new Date());
            walletPayLog.setCreateUser("System");
            walletPayLog.setPayStatus(PayStatus.unpaid.getName());
            walletPayLog.setPayType(PayType.CT_ALI.getValue());
            walletPayLog.setTitle("get");
            walletPayLog.setUid(user.getId());
            walletPayLog.setTotalFee(totalTee);
            walletPayLog = wplDao.saveOrUpdate(walletPayLog);
            //2.充值
            // BCOrder bcOrder = butil.aliPay(Integer.parseInt((totalTee * 100) + ""), billNo, "用户余额充值！", optional);
            //3.存入交易记录(order)
            order.setUid(user.getUid());
            //为订单赋值
            order.setProvince("");
            order.setProvinceID(1);
            order.setCity("");
            order.setCityID(1);
            order.setArea("");
            order.setAreaID(1);
            order.setAddress("");
            order.setType("userget");
            order.setUid(user.getUid());
            order.setCreateDate(new Date());
            order.setCoiUid(GuidUtil.getGuid());
            order.setOrderStatus(PayStatus.unpaid.getName());
            order.setOrderNo(billNo);
            order.setUpdateDate(new Date());
            order.setUpdateUser(user.getUsername());
            order.setIsPay("0");
            order.setUserName(user.getUsername());
            order.setUserPhone(user.getTel());
            order.setOrderChanel(PayType.CT_UN.getName());
            order.setTotalFee((int) ((totalTee * 100)));
            order.setShoppingCarts(null);
            order.setCouponID(null);
            order.setBill(null);
            order.setBillType(null);
            order.setBillContent(null);
            order = orderDao.saveOrUpdate(order);
            //存入支付数据
            OnlinePayLog opl = new OnlinePayLog();
            opl.setCreateDate(new Date());
            opl.setBillNo(order.getOrderNo());
            opl.setCreateUser(user.getUsername());
            opl.setIdKey(GuidUtil.getGuid());
            opl.setPayStatus(PayStatus.unpaid.getName());
            opl.setPayType(order.getPayType());
            opl.setTitle("用户充值");
            opl.setTotalFee(order.getTotalFee());
            onlinePayLogDAO.saveOrUpdate(opl);
            code = "1";
            msg = "下单成功！";
        } else {
            msg = "未查询到用户信息，充值失败！";
        }
        return resultMsg.mapToJson(code, msg, order);
    }

    /**
     * 提现
     *
     * @param accessToken token
     * @param totalFee    提现金额
     * @return
     */
    @ApiOperation(value = "提现", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "accessToken", required = true, dataType = "String"),
            @ApiImplicitParam(name = "totalFee", value = "提现金额", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "Integer")
    })
    @ResponseBody
    @RequestMapping(value = "/wallet/reimburse", method = RequestMethod.GET)
    public String reimburse(String accessToken, float totalFee, int type) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        String billNo = OrderUtil.getOrderNo();
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            //0.判断提现金额是否大于余额
            if (totalFee <= user.getBalance()) {
                //1.存入交易记录（order)
                Order order = new Order();
                order.setUid(user.getUid());
                //为订单赋值
                order.setOrderNo(billNo);
                order.setProvince("");
                order.setProvinceID(1);
                order.setCity("");
                order.setCityID(1);
                order.setArea("");
                order.setAreaID(1);
                order.setAddress("");
                order.setUid(user.getUid());
                order.setCreateDate(new Date());
                order.setCoiUid(GuidUtil.getGuid());
                order.setOrderStatus(PayStatus.unpaid.getName());
                order.setUpdateDate(new Date());
                order.setUpdateUser(user.getUsername());
                order.setIsPay("0");
                order.setUserName(user.getUsername());
                order.setUserPhone(user.getTel());
                order.setOrderChanel(PayType.CT_UN.getName());
                order.setTotalFee((int) (totalFee * 100));
                order.setShoppingCarts(null);
                order.setCouponID(null);
                order.setBill(null);
                order.setBillType(null);
                order.setBillContent(null);
                order = orderDao.saveOrUpdate(order);
                //2.存入交易记录
                WalletPayLog walletPayLog = new WalletPayLog();
                walletPayLog.setBillNo(billNo);
                walletPayLog.setCreateTimestamp(new Date());
                walletPayLog.setCreateUser("System");
                walletPayLog.setPayStatus(PayStatus.unpaid.getName());
                walletPayLog.setPayType(PayType.CT_UN.getName());
                walletPayLog.setTitle("out");
                walletPayLog.setUserPayStatus("commission");
                walletPayLog.setUid(user.getId());
                walletPayLog.setTotalFee((int) (totalFee * 100));
                walletPayLog = wplDao.saveOrUpdate(walletPayLog);

            } else {
                code = "2";
                msg = "余额不足！";
            }
        } else {
            code = "2";
            msg = "无效的token！";
            return resultMsg.mapToJson(code, msg, null);
        }

        return resultMsg.mapToJson(code, msg, result);
    }

    /**
     * 设置/修改支付密码
     *
     * @param accessToken
     * @param payPassword
     * @param msgCode
     * @return
     */
    @ApiOperation(value = "设置/修改支付密码", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "payPassword", value = "支付密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "msgCode", value = "短信验证码", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/wallet/setPayPassword", method = RequestMethod.POST)
    public String reimburse(String accessToken, String payPassword, String msgCode, HttpServletRequest req) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        if (user != null) {
            if (msgCode.equals(req.getSession(false).getAttribute(user.getTel()).toString())) {
                payPassword = passwordEncoder.encodePassword(payPassword, saltSource.getSalt(user));
                user.setPayPwd(payPassword);
                if (userDao.saveOrUpdate(user) != null) {
                    code = "1";
                    msg = "更新密码成功！";
                } else {
                    msg = "系统异常，更新失败！";
                }
            } else {
                msg = "验证码不正确！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, null);
    }

    /**
     * 查询分销设置
     *
     * @return
     */
    @ApiOperation(value = "设置/查询分销设置", notes = "")
    @ResponseBody
    @RequestMapping(value = "/wallet/minmoneylimit", method = RequestMethod.POST)
    public String minmoney() {
        String code = "2";
        String msg = "处理异常！";
        Minmoneylimit m = new Minmoneylimit();
        m = minmoneylimitDAO.find(1);
        if (m != null) {
            code = "1";
            msg = "查询分销设置成功！";
        } else {
            code = "1";
            msg = "未查询到分销设置信息！";
        }
        return resultMsg.mapToJson(code, msg, m);
    }
}
